// 导入db模块r_text
const db = require('../config/db');

// 回复类
class Reply {
    // 发表回复
    add(r_id, r_text, r_create_time, from_user_id, to_user_id, article_id,c_id){
        return new Promise((resolve,reject)=>{
            let sql = `insert into db_reply(r_id, r_text, r_create_time, from_user_id, to_user_id, article_id,c_id) 
             values('${r_id}','${r_text}','${r_create_time}','${from_user_id}','${to_user_id}','${article_id}','${c_id}')`;

             db.query(sql)
             .then(
                (result)=>{
                    // console.log(result)
                    if(result.affectedRows === 1) {
                        resolve({
                            code: 200,
                            msg: '发表回复成功。'
                        })
                    }
                    else {
                        resolve({
                            code: -1,
                            msg: '发表回复失败。'
                        })
                    }
                    
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '发表回复失败。',
                        err 
                    })
                }
             )
        })
    }

    // 删除回复
    remove(r_id,from_user_id){
        return new Promise((resolve,reject)=>{
            let sql = `delete from db_reply where r_id = '${r_id}' and from_user_id = '${from_user_id}'`
            db.query(sql)
            .then(
                (result)=>{
                    // console.log(result);
                    if(result.affectedRows === 1) {
                        resolve({
                            code: 200,
                            msg: '删除回复成功。'
                        })
                    }
                    else {
                        resolve({
                            code: -1,
                            msg: '您不能删除别人的回复。'
                        })
                    }
                   
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '删除回复失败。',
                        err 
                    })
                }
            )
        })
    }

    // 获取回复
    list(article_id, c_id){
        return new Promise((resolve,reject)=>{
            let sql = `select * from db_reply where article_id='${article_id}' and c_id = '${c_id}'`;
            db.query(sql)
            .then(
                (rows)=>{
                    resolve({
                        code: 200,
                        msg: '获取回复列表成功。',
                        result: rows 
                    })
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '获取回复列表失败。',
                        err
                    })
                }
            )
        })
    }
}

module.exports = new Reply();